package so.shanku.essential.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.*;
import net.tsz.afinal.json.JsonMap;
import net.tsz.afinal.json.JsonMapOrListJsonMap2JsonUtil;
import net.tsz.afinal.json.JsonParseHelper;
import net.tsz.afinal.annotation.view.ViewInject;
import so.shanku.essential.R;
import so.shanku.essential.activity.base.BaseUIActivity;
import so.shanku.essential.adapter.ShopCartAdapter;
import so.shanku.essential.getdata.*;
import so.shanku.essential.utils.Constant;
import so.shanku.essential.utils.ExtraKeys;
import so.shanku.essential.utils.StringUtil;
import so.shanku.essential.utils.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Jaelyn on 2015/9/19 0019.
 * 购物车
 */
public class ShoppingCartActivity extends BaseUIActivity {

    private static final int MAX_NUM = 999;
    /**
     * 底部全选
     */
    @ViewInject(id = R.id.totle_selected_cb, click = "totle_selected_cb_click")
    private TextView totle_selected_id;
    /**
     * 显示总价格
     */
    @ViewInject(id = R.id.totle_money_tv)
    private TextView totle_money;
    /**
     * 结算
     */
    @ViewInject(id = R.id.ensure_order_tv, click = "ensure_order_tv_click")
    private TextView ensure_order_tv;
    /**
     * 商品的列表页
     */
    @ViewInject(id = R.id.goods_list)
    private ListView goods_list;
    @ViewInject(id = R.id.nodata_layout)
    private LinearLayout nodata_layout;

    private ShopCartAdapter shopCartAdapter;

    /**
     * 总价格
     */
    private String totleMoney;
    private JsonMap datas;
    /**
     * 商品集合
     */
    private ArrayList<JsonMap<String,Object>> productList=new ArrayList<JsonMap<String, Object>>();

    private boolean isRequestData = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shopcart_layout);
        setCenter_title(R.string.shopcart);
        setBtn_menuText(R.string.delete, getData_deleteToUserCart);
        loadingToast.show();
        getServerData();
    }


    @Override
    protected void onRestart() {
        super.onRestart();
        if (isRequestData) {
            getServerData();
            isRequestData = false;
        }
    }


    /**
     * 获取购物车信息
     */
    private void getServerData() {
        if (datas != null && datas.size() > 0) {
        }

        Map<String, Object> params = new HashMap<String, Object>();

        params.put("userId", Utils.getUserId(mContext));
        GetDataQueue queue = new GetDataQueue();
        queue.setActionName(GetDataConfing.GetAction_GetShoppingCartByUserId);
        queue.setParamsNoJson(params);
        queue.setCallBack(callBack);
        queue.setWhat(GetDataConfing.What_GetShoppingCartByUserId);
        getDataUtil.getData(queue);
    }

    /**
     * 通知其他页面 购物车数量改变
     */
    private void sendShopCartNumChangeBroadCast() {
        sendBroadcast(new Intent(Constant.ACAT_SHOPCARTNUMCHANGE));
    }

    private IGetServicesDataCallBack callBack = new IGetServicesDataCallBack() {
        @Override
        public void onLoaded(GetDataQueue entity) {
            if (entity.isOk()) {
//                if (ShowGetDataError.isCodeSuccess(mContext, entity.getInfo())) {
                if (entity.what == GetDataConfing.What_GetShoppingCartByUserId ||
                        entity.what == GetDataConfing.What_UpdateShoppingCartListByProductId ||
                        entity.what == GetDataConfing.What_updateShoppingCartProductAmountById ||
                        entity.what == GetDataConfing.What_UpdateShoppingCartByShopId) {
                    if (datas != null) {
                        datas.clear();
                    }
                    datas = JsonParseHelper.getJsonMap_JsonMap(entity.getInfo(), JsonKeys.Key_Info);
                    flushDatas();
                } else if (entity.what == GetDataConfing.What_DeleteShoppingCartProduct) {
                    getServerData();
                }
                sendShopCartNumChangeBroadCast();
//
            } else {
                ShowGetDataError.showNetError(mContext);
            }
            validateData();
            loadingToast.dismiss();
        }

    };

    private void validateData() {
        if (datas == null || datas.size() == 0) {
            nodata_layout.setVisibility(View.VISIBLE);
            goods_list.setVisibility(View.GONE);
        } else {
            goods_list.setVisibility(View.VISIBLE);
            nodata_layout.setVisibility(View.GONE);
        }
    }

    private void flushDatas() {
        productList = (ArrayList<JsonMap<String, Object>>) datas.getList_JsonMap("shoppingCartList");
        shopCartAdapter = new ShopCartAdapter(mContext);
        shopCartAdapter.setDatas(productList);
        goods_list.setAdapter(shopCartAdapter);
        shopCartAdapter.setOnItemClickListener(onItemClickListener);
        totle_selected_id.setSelected(datas.getBoolean("isTotleChecked"));
        //setListViewHeightBasedOnChildren(goods_list);
        setEnsure_order_tv();
    }

    /**
     * 底部全选
     *
     * @param view
     */
    public void totle_selected_cb_click(View view) {
        selectBrandStauChange(-1, 0);
    }

    /**
     * 确认订单
     *
     * @param view
     */
    public void ensure_order_tv_click(View view) {
        if (Utils.isHasLogin(this)) {//&&TextUtils.isEmpty(Utils.getUserPhone(this))
            isRequestData = true;
            gotoLogin();
            return;
        }
        if (Double.parseDouble(totleMoney)<0.01) {
            toast.showToast(R.string.shopingcart_empty);
            return;
        }

        List<JsonMap<String, Object>> brandGoodsList = datas.getList_JsonMap("shoppingCartList");
        List<JsonMap<String, Object>> selectProductList = new ArrayList<JsonMap<String, Object>>();
        boolean isAllValidate = true;
        for (JsonMap brandGoods : brandGoodsList) {
            List<JsonMap<String, Object>> goodsList = brandGoods.getList_JsonMap("shoppingCartList");
            for (JsonMap jsonMap : goodsList) {
                if (jsonMap.getBoolean("isChecked")) {
                    selectProductList.add(jsonMap);
                    boolean isEnable = jsonMap.getBoolean("isEnable");
                    if (isEnable) {
                        int stock = jsonMap.getInt("stock");
                        if (stock < 0) {
                            isAllValidate=false;
                            break;
                        }
                    } else {
                        isAllValidate=false;
                        break;
                    }

                }
            }
        }
        if (!isAllValidate) {
            toast.showToast(R.string.shopcart_container_invalidate);
            return;
        }
        JsonMapOrListJsonMap2JsonUtil<String, Object> util = new JsonMapOrListJsonMap2JsonUtil<String, Object>();
        Intent intent = new Intent(this, ShopAddOrderActivity.class);
        intent.putExtra(ExtraKeys.Key_Msg1, totleMoney);
        intent.putExtra(ExtraKeys.Key_Msg2, util.listJsonMap2Json(selectProductList));
//		zongjia = intent.getDoubleExtra(ExtraKeys.Key_Msg1, 0.00);
//		selectProJson = intent.getStringExtra(ExtraKeys.Key_Msg2);
//
        startActivityForResult(intent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            getServerData();
        }
    }

    public void setEnsure_order_tv() {
        try {
            totleMoney=StringUtil.getFormatMoney(datas.getStringNoNull("totalPrice"));
            String totle_money_formart=String.format(getString(R.string.totle_money),totle_money );
            totle_money.setText(totle_money_formart);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            ensure_order_tv.setEnabled(false);
        }
    }

    String productIds = "";

    /**
     * 已登陆的用户将要删除的购物信息加入到发往服务器
     */
    private View.OnClickListener getData_deleteToUserCart = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (datas == null) {
                return;
            }
            List<JsonMap<String, Object>> brandGoodsList = datas.getList_JsonMap("shoppingCartList");
            productIds = "";
            for (JsonMap brandGoods : brandGoodsList) {
                List<JsonMap<String, Object>> goodsList = brandGoods.getList_JsonMap("shoppingCartList");
                for (JsonMap jsonMap : goodsList) {
                    if (jsonMap.getBoolean("isChecked")) {
                        String orderId = jsonMap.getStringNoNull("productId");
                        productIds = orderId + "," + productIds;
                    }
                }
            }
            if (TextUtils.isEmpty(productIds)) {
                return;
            }
            productIds = productIds.substring(0, productIds.lastIndexOf(","));
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle(R.string.shopping_prompt);
            builder.setMessage(R.string.shopping_confirm_delete);
            builder.setPositiveButton(R.string.cancel,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface arg0, int arg1) {
                        }
                    });
            builder.setNegativeButton(R.string.ensure,
                    new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface arg0, int arg1) {
                            deleteShopGoods();
                        }
                    });
            builder.show();
        }
    };

    /**
     * 删除善品
     */
    private void deleteShopGoods() {
        loadingToast.show();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("productIds", productIds);
        params.put("userId", Utils.getUserId(mContext));
        GetDataQueue queue = new GetDataQueue();
        queue.setActionName(GetDataConfing.Action_DeleteShoppingCartProduct);
        queue.setCallBack(callBack);
        queue.setParamsNoJson(params);
        queue.setWhat(GetDataConfing.What_DeleteShoppingCartProduct);
        getDataUtil.getData(queue);
    }

    ShopCartAdapter.OnItemClickListener onItemClickListener = new ShopCartAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(int position, Constant.ShopCartItemCompontType shopCartitemType, int index) {
            if (shopCartitemType == Constant.ShopCartItemCompontType.SELECT_GOODS_BRAND) {
                selectBrandStauChange(position, 1);
            } else if (shopCartitemType == Constant.ShopCartItemCompontType.SELECT_GOODS_ITEM) {
                selectStauChange(position, index);
            } else if (shopCartitemType == Constant.ShopCartItemCompontType.ADD_NUM) {
                goodsNumChange(position, shopCartitemType, index);
            } else if (shopCartitemType == Constant.ShopCartItemCompontType.SUB_NUM) {
                goodsNumChange(position, shopCartitemType, index);
            } else if (shopCartitemType == Constant.ShopCartItemCompontType.NUM_EDIT) {
                showEditNumDialog(position, shopCartitemType, index);
            } else if (shopCartitemType == Constant.ShopCartItemCompontType.CLICK_GOODS_ITEM) {
                showGoodsDetail(position, index);
            } else if (shopCartitemType == Constant.ShopCartItemCompontType.CLICK_BRAND_NAME) {
                showShopDetail(position, index);
            }
        }
    };


    /**
     * 跳转到店铺详情页
     *
     * @param position
     * @param index
     */
    private void showShopDetail(int position, int index) {
        JsonMap jsonMap = productList.get(position);
        String vendorId = jsonMap.getStringNoNull("shopId");
        seeShopDetail(vendorId);
    }

    /**
     * 跳转到商品详情
     *
     * @param position
     * @param index
     */
    private void showGoodsDetail(int position, int index) {
        JsonMap jsonMap = productList.get(position).getList_JsonMap("shoppingCartList").get(index);
        seeProductDetail(jsonMap.getStringNoNull("productId"));
    }

    /**
     * 一级或者二级列表 状态改变
     *
     * @param position
     * @param i        0：一级 底部选项 1:2级
     */
    private void selectBrandStauChange(int position, int i) {

        productIds = "";

        int isChecked = 0; //1是全不选否则就全选
        if (i == 1) {
            List<JsonMap<String, Object>> goodsList = productList.get(position).getList_JsonMap("shoppingCartList");
            if (productList.get(position).getBoolean("isShopChecked")) {
                isChecked = 1;
            } else {
                isChecked = 0;
            }
            for (JsonMap jsonMap : goodsList) {
                if (jsonMap.getBoolean("isChecked")) {
                    String orderId = jsonMap.getStringNoNull("productId");
                    productIds = orderId + "," + productIds;
                }
            }

        } else {
            if (datas.getBoolean("isTotleChecked")) {
                isChecked = 1;
            } else {
                isChecked = 0;
            }
            for (JsonMap brandGoods : productList) {
                List<JsonMap<String, Object>> goodsList = brandGoods.getList_JsonMap("shoppingCartList");
                for (JsonMap jsonMap : goodsList) {
                    if (jsonMap.getBoolean("isChecked")) {
                        String orderId = jsonMap.getStringNoNull("productId");
                        productIds = orderId + "," + productIds;
                    }
                }
            }
        }

        if (TextUtils.isEmpty(productIds)) {
            return;
        }
        productIds = productIds.substring(0, productIds.lastIndexOf(","));

        Map<String, Object> params = new HashMap<String, Object>();

        params.put("userId", Utils.getUserId(this));
        params.put("productIds", productIds);
        params.put("isChecked", isChecked);
        GetDataQueue queue = new GetDataQueue();
        queue.setActionName(GetDataConfing.GetAction_UpdateShoppingCartByShopId);
        queue.setParamsNoJson(params);
        queue.setCallBack(callBack);
        queue.setWhat(GetDataConfing.What_UpdateShoppingCartByShopId);
        getDataUtil.getData(queue);
    }

    private Dialog dialogLogin;
    private EditText et_product_pronum;
    private ImageView iv_pronum_jian;
    private ImageView iv_pronum_jia;
    private ImageView bt_quxiao;
    private ImageView bt_queding;
    private TextView tv_price;
    private TextView tv_pronum;
    int pronum;
    private String productId;

    private void showEditNumDialog(int position, Constant.ShopCartItemCompontType shopCartitemType, int index) {
        List<JsonMap<String, Object>> goodsList = datas.getList_JsonMap("shoppingCartList");
        JsonMap jsonMap = goodsList.get(position).getList_JsonMap("shoppingCartList").get(index);
        productId = jsonMap.getStringNoNull("productId");
        dialogLogin = new Dialog(this, R.style.ShopDialogStyle);
        dialogLogin.setCanceledOnTouchOutside(false);
        dialogLogin.setCancelable(true);
        View view = getLayoutInflater().inflate(R.layout.item_shoppingcart_editnum, null);
        et_product_pronum = (EditText) view
                .findViewById(R.id.i_s_et_product_pronum);
        iv_pronum_jian = (ImageView) view
                .findViewById(R.id.i_s_iv_pronum_jian);
        iv_pronum_jia = (ImageView) view
                .findViewById(R.id.i_s_iv_pronum_jia);
        bt_quxiao = (ImageView) view
                .findViewById(R.id.i_s_bt_quxiao);
        bt_queding = (ImageView) view
                .findViewById(R.id.i_s_bt_queding);
        tv_price = (TextView) view
                .findViewById(R.id.i_s_tv_price);
        tv_pronum = (TextView) view
                .findViewById(R.id.i_s_tv_pronum);
        dialogLogin.setContentView(view);

        tv_price.setText(StringUtil.getFormatMoneyWithSign(jsonMap.getStringNoNull("salePrice")));
        et_product_pronum.setText(jsonMap.getStringNoNull("amount"));
        tv_pronum.setVisibility(View.GONE);
        // tv_pronum.setText("x" + et_product_pronum.getText());
        dialogLogin.show();

        iv_pronum_jia.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                pronum = Integer.parseInt(et_product_pronum
                        .getText().toString());
                if (pronum < MAX_NUM) {
                    pronum = pronum + 1;
                }
//								pronum = 1000;
                show();
            }
        });
        iv_pronum_jian
                .setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        pronum = Integer
                                .parseInt(et_product_pronum
                                        .getText().toString());
                        if (pronum > 1) {
                            pronum = pronum - 1;
                        }
                        show();
                    }
                });
        bt_quxiao.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialogLogin.cancel();
            }
        });

        bt_queding.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (!"".equals(et_product_pronum.getText()
                        .toString())) {
                    pronum = Integer.parseInt(et_product_pronum
                            .getText().toString());
                    if (pronum > 0) {
                        dialogLogin.cancel();
                        updateGoodsNum(pronum, productId);
                    }
                }

            }
        });
    }

    public void show() {
        et_product_pronum.setText(pronum + "");
        // tv_pronum.setText(pronum + "");
    }

    private void goodsNumChange(int position, Constant.ShopCartItemCompontType shopCartitemType, int index) {

        List<JsonMap<String, Object>> goodsList = datas.getList_JsonMap("shoppingCartList");
        JsonMap jsonMap = goodsList.get(position).getList_JsonMap("shoppingCartList").get(index);
        int num = jsonMap.getInt("amount");
        if (shopCartitemType == Constant.ShopCartItemCompontType.ADD_NUM) {
            if (num >= MAX_NUM) {
                return;
            }
            num++;
        } else {
            if (num <= 1) {
                return;
            }
            num--;
        }
        //String productId = jsonMap.getStringNoNull("ProductId");
        productId = jsonMap.getStringNoNull("productId");
        updateGoodsNum(num, productId);
    }

    /**
     * 更新数量
     *
     * @param num
     * @param productId 订单编号
     */
    private void updateGoodsNum(int num, String productId) {
        Map<String, Object> params = new HashMap<String, Object>();
        // params.put("userAccount", app.getUserId());
        params.put("productId", productId);
        params.put("amount", num);
        params.put("userId", Utils.getUserId(this));
        GetDataQueue queue = new GetDataQueue();
        queue.setActionName(GetDataConfing.Action_updateShoppingCartProductAmountById);
        queue.setCallBack(callBack);
        queue.setParamsNoJson(params);
        queue.setWhat(GetDataConfing.What_updateShoppingCartProductAmountById);
        getDataUtil.getData(queue);
    }

    /**
     * 商品状态的变化 {CheckendVO:[{id:80450},{id:80456}]}
     *
     * @param position
     * @param index
     */
    private void selectStauChange(int position, int index) {
        String productId = productList.get(position).getList_JsonMap("shoppingCartList")
                .get(index).getStringNoNull("productId");

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("productId", productId);
        params.put("userId", Utils.getUserId(mContext));
        GetDataQueue queue = new GetDataQueue();
        queue.setActionName(GetDataConfing.GetAction_UpdateShoppingCartListByProductId);
        queue.setParamsNoJson(params);
        queue.setCallBack(callBack);
        queue.setWhat(GetDataConfing.What_UpdateShoppingCartListByProductId);
        getDataUtil.getData(queue);
    }
}